﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SAKS.Models;
using SAKS.ViewModels;
using SAKS.IServices;
using SAKS.ActionFilters;


namespace SAKS.Controllers
{
    [Authorize]
    public class UserController : ControllerBase
    {
        public IUserServices UserServices { get; set; }
        public IMessageServices MessageServices { get; set; }

        private string UserName { get; set; }

        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
            UserServices.Session = GetCurrentSession(requestContext);
            UserServices.UserName = requestContext.HttpContext.User.Identity.Name;
            UserName = requestContext.HttpContext.User.Identity.Name;
            MessageServices.Session = GetCurrentSession(requestContext);

        }

        public ActionResult Index()
        {
            return View();
        }
        public ActionResult MyMessages()
        {
            return View();
        }
        public ActionResult MyProjects()
        {
            var projects = UserServices.GetUserProjects();
            var projectList = ProjectMapper.ToListModel(projects);
            return View(projectList);
        }

        public ActionResult MyAccount()
        {
            return View();
        }

        #region Info

        public ActionResult CreateInfo()
        {
            return View();
        }
        [HttpPost]
        [NeedsPersistence]
        public ActionResult CreateInfo(PersonInfoCreateUpdateModel model)
        {
            var personinfo = PersonInfoMapper.ToPersonInfo(model);
            UserServices.AddPersonInfo(HttpContext.User.Identity.Name,personinfo);
            return RedirectToAction("Index", "Home");
        }


        public ActionResult ajaxPersonInfoByUserName(string username)
        {
            var info = UserServices.GetPersonInfoByUserName(username);
            if (info != null)
            {
                var data = PersonInfoMapper.ToCreateUpdateModel(info);
                var result =  new AjaxResponse{State = "Succeed",Data = data,Message = ""};
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            else
                return Json(new AjaxResponse { State = "Failure", Message = "信息尚未录入" }, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        [NeedsPersistence]
        public ActionResult ajaxUpdatePersonInfo(PersonInfoCreateUpdateModel model)
        {
            var personinfo = PersonInfoMapper.ToPersonInfo(model);
            if (UserServices.UpdatePersonInfo(personinfo))
                return Json(new AjaxResponse { State = "Succeed", Message = "更新成功" });
            else
                return Json(new AjaxResponse { State = "Failure", Message = "更新失败" });
        }


        #endregion

        #region 获取消息列表

        //获取未读邮件列表

        public ActionResult MessagesUnRead(DataTableParameter param)
        {
            int? _start = param.iDisplayStart ;
            int? _pageSize = param.iDisplayLength;

            int start = _start ?? 0;
            int pageSize = _pageSize ?? 20;

            var username = HttpContext.User.Identity.Name;
            int? totalRecords = new int?();

            var ret = MessageServices.GetMessagesUnRead(
                        username,
                        start,
                        pageSize,
                        out totalRecords
                        );
            Session["unreadmessagecount"] = totalRecords;
            var json = BuildJsonResult(param, totalRecords, ret);
            return json;
        }

        private JsonResult BuildJsonResult(DataTableParameter param, int? totalRecords, object[] ret)
        {
            var json = Json(
                new dataTableJson
                {
                    sEcho = param.sEcho,
                    iTotalRecords = totalRecords,
                    iTotalDisplayRecords = totalRecords,
                    aaData = ret
                },
                JsonRequestBehavior.AllowGet
            );
            return json;
        }

        //获取已读邮件列表
        public ActionResult MessagesRead(DataTableParameter param)
        {
            int? _start = param.iDisplayStart ;
            int? _pageSize = param.iDisplayLength;

            int start = _start ?? 0;
            int pageSize = _pageSize ?? 20;

            var username = HttpContext.User.Identity.Name;
            int? totalRecords = new int?();

            var ret = MessageServices.GetMessagesRead(
                        username,
                        start,
                        pageSize,
                        out totalRecords
                        );
            var json = BuildJsonResult(param, totalRecords, ret);
            return json;
        }

        //获取发送过的邮件
        public ActionResult MessagesSent(DataTableParameter param)
        {
            int? _start = param.iDisplayStart / param.iDisplayLength;
            int? _pageSize = param.iDisplayLength;

            int start = _start ?? 0;
            int pageSize = _pageSize ?? 20;

            var username = HttpContext.User.Identity.Name;
            int? totalRecords = new int?();

            var ret = MessageServices.GetMessagesSent(
                        username,
                        start,
                        pageSize,
                        out totalRecords
                        );
            var json = BuildJsonResult(param, totalRecords, ret);
            return json;
        }

        #endregion

        #region 读消息
        [NeedsPersistence]
        public ActionResult ReadMessageUnRead(Guid id)
        {
            var message = MessageServices.GetMessageReceived(id);
            ReduceUnReadMessageCount();
            return Json(message, JsonRequestBehavior.AllowGet);
        }

        void ReduceUnReadMessageCount()
        {
            int count;
            if (HttpContext.Session["unreadmessagecount"] != null)
            {
                count = int.Parse(HttpContext.Session["unreadmessagecount"].ToString());
            }
            else
            {
                count = MessageServices.GetMessagesUnReadCount(UserName);            
            }
            HttpContext.Session["unreadmessagecount"] = count > 0 ? count - 1 : 0;
        }

        [NeedsPersistence]
        public ActionResult ReadMessageRead(Guid id)
        {
            var message = MessageServices.GetMessageReceived(id);
            return Json(message, JsonRequestBehavior.AllowGet);
        }
        [NeedsPersistence]
        public ActionResult ReadMessageSent(Guid id)
        {
            return Json(MessageServices.GetMessageSent(id),JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region 删除消息
        [NeedsPersistence]
        public string DeleteMessageSent(Guid id)
        {
            try
            {
                MessageServices.DeleteMessageSent(id);
                return "ok";
            }
            catch (Exception e)
            {
                return e.Message;
            }
        }
        [NeedsPersistence]
        public string DeleteMessageUnRead(Guid id)
        {
            try
            {
                MessageServices.DeleteMessageReceived(id);
                ReduceUnReadMessageCount();
                return "ok";
            }
            catch (Exception e)
            {
                return e.Message;
            }
           
        }
        [NeedsPersistence]
        public string DeleteMessageRead(Guid id)
        {
            try
            {
                MessageServices.DeleteMessageReceived(id);
                return "ok";
            }
            catch (Exception e)
            {
                return e.Message;
            }

        }

        #endregion

        #region 发消息

        [NeedsPersistence]
        [HttpPost]
        public ActionResult SendMessage()
        {
            var to = Request["To"];
            var from = HttpContext.User.Identity.Name;
            var subject = Request["Subject"];
            var content = Request["Content"];
            if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(subject))
            {
                MessageServices.SendMessage(to, from, subject, content);
                return Json(new { Message = "发送成功" });
            }
            else
            {
                return Json(new { Message = "发送失败 - 主题或收件人为空" });
            }
        }
        #endregion

    }
}
